#include "t_at_ringbuffer.h"

rbuf_err_t rbuf_init(rbuf *me)
{
    me->head = 0;
    me->tail = 0;
    me->size = 0;
    return RBUF_OK;
}
rbuf_err_t rbuf_push(rbuf *me, rdata_buff *data) {
    if (data == NULL) return RBUF_ERROR;  // 检查空指针

    // 完全覆盖目标缓冲区
    memcpy(&me->ringbuffer[me->tail], data, sizeof(rdata_buff));

    me->tail = (me->tail + 1) % URC_RING_SIZE;
    if (me->size < URC_RING_SIZE) {
        me->size++;
    } else {
        me->head = (me->head + 1) % URC_RING_SIZE;  // 队列满时移动 head
    }
    return RBUF_OK;
}

rbuf_err_t rbuf_pop(rbuf *me, rdata_buff *data) {
    if (rbuf_is_empty(me) != RBUF_OK || data == NULL) {
        return RBUF_EMPTY;
    }

    // 复制数据到输出
    memcpy(data, &me->ringbuffer[me->head], sizeof(rdata_buff));

    // 清理缓冲区（可选，如果后续 push 会覆盖）
    memset(&me->ringbuffer[me->head], 0, sizeof(rdata_buff));

    me->head = (me->head + 1) % URC_RING_SIZE;
    me->size--;
    return RBUF_OK;
}

rbuf_err_t rbuf_clear(rbuf *me)
{
    me->head = 0;
    me->tail = 0;
    me->size = 0;
    return RBUF_OK;
}

rbuf_err_t rbuf_is_empty(rbuf *me)
{
    if (me->size == 0) {
        return RBUF_EMPTY;
    }
    return RBUF_OK;
}

rbuf_err_t rbuf_is_full(rbuf *me)
{
    if (me->size == URC_RING_SIZE) {
        return RBUF_FULL;
    }
    return RBUF_OK;
}
